package cn.itsource.pethome.service.impl;

import cn.itsource.pethome.domain.BaseDomain;
import cn.itsource.pethome.domain.Department;
import cn.itsource.pethome.mapper.EmployeeMapper;
import cn.itsource.pethome.query.BaseQuery;
import cn.itsource.pethome.result.JSONResult;
import cn.itsource.pethome.service.BaseService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
public class BaseServiceImpl<T  extends BaseDomain, K extends BaseQuery> implements BaseService<T, K> {
    @Autowired
    private Mapper<T> mapper;
    @Override
    public T selectById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }
    @Override
    public JSONResult pagelist(K k) {
        Page<T> objects = PageHelper.startPage(k.getCurrent(), k.getSize());
        List<T> selectAll = mapper.selectAll();
        PageInfo<T> pageInfo = new PageInfo<>(selectAll);
        return JSONResult.success(pageInfo);
    }
    @Override
    public List<T> list() {
        List<T> selectAll = mapper.selectAll();
        return selectAll;
    }

    @Override
    public JSONResult saveOrUpdate(T t) {
        if(t.getId() != null){
            //编辑操作
           mapper.updateByPrimaryKey(t);
        }else{
            //新增操作
            mapper.insert(t);
        }
        return JSONResult.success();
    }

    @Override
    public JSONResult deleteBatch(K k) {
        Long[] ids = k.getIds();
        for (Long id : ids) {
            mapper.deleteByPrimaryKey(id);
        }
        return JSONResult.success();
    }

    @Override
    public JSONResult delete(Long id) {
        mapper.deleteByPrimaryKey(id);
        return JSONResult.success();
    }
    public void deleteDeptDeep(Long deptid,String foreignKey){
        /**
         *
         * 递归删除
         1.找到parentId等于10的所有记录,list
         2.循环list,重复第一步
         3.如果没有子节点时删除自己
         */
        Example example = new Example(Department.class);
        example.and().andEqualTo(foreignKey,deptid);
        List<T> list = mapper.selectByExample(example);
        for (T t : list) {
            Long id = t.getId();
            deleteDeptDeep(id,foreignKey);
        }
        mapper.deleteByPrimaryKey(deptid);
    }
}
